package main

import (
	"database/sql"
      "fmt"
	_ "github.com/go-sql-driver/mysql"
	  "github.com/jmoiron/sqlx"
)
var DB *sqlx.DB
func  initDb() error  {
	var err error
	dsn := "root:root@tcp(localhost:3306)/golang_db"
	DB, err = sqlx.Open("mysql", dsn)
	if err != nil {
		return err
	}
	DB.SetMaxOpenConns(100)
	DB.SetMaxIdleConns(16)
	return nil
}
type User struct {
	Id int64 `db:"id"`
	Name sql.NullString `db:"name"`
	Age int `db:"age"`
}
func testQuery(){
	sqlstr := "select id, name, age from user where id = ?"
	var user User
	err := DB.Get(&user,sqlstr,2)
	if err != nil {
		fmt.Printf("get failed, err:%v\n",err)
		return
	}
	fmt.Printf("user:%#v\n",user)
}
func testQueryMulti(){
	sqlstr := "select id,name,age from user where id>?"
	var user []User
	err := DB.Select(&user,sqlstr,1)
	if err != nil {
		fmt.Printf("get failed,err:%v\n",err)
		return
	}
    fmt.Printf("user:%#v\n",user)
}
func main(){
  err := initDb()
  if err != nil {
	  fmt.Printf("init db failed,err:%v\n",err)
  }
  testQueryMulti()
}